package com.web.security.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;

import com.web.security.user.WebUser;


public class WebAuthenticationProcessingFilter extends AuthenticationProcessingFilter{

private static final Logger LOGGER = Logger.getLogger(WebAuthenticationProcessingFilter.class);

	
	@Override
	protected void onSuccessfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, Authentication authResult)
			throws IOException {
		LOGGER.info("===================== Start Authentication -- 1");
		if(request.getSession().getAttribute("error") != null){
			request.getSession().removeAttribute("error");
		}
		super.onSuccessfulAuthentication(request, response, authResult);
	}
	
	@Override
	protected void onPreAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException,
			IOException {
	
		super.onPreAuthentication(request, response);
		LOGGER.info("======================== Start Authentication -- 2");
	}
	
	@Override
	protected void successfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, Authentication authResult)
			throws IOException, ServletException {
		LOGGER.info("======================== Start Authentication -- 3");
		SecurityContextHolder.getContext().setAuthentication(authResult);
		
		WebUser user = (WebUser) authResult.getPrincipal();
		//unsuccessfulAuthentication(request, response, new LockedException("System is currently locked for End of Day process."));
		super.successfulAuthentication(request, response, authResult);
	}
	
	@Override
	protected void onUnsuccessfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException failed)
			throws IOException {
		LOGGER.info("======================== Start Authentication -- 4");
		request.getSession().setAttribute("error", true);
		super.onUnsuccessfulAuthentication(request, response, failed);
	}
}
